package g_phoenixLimiter

import (
	"testing"
	"time"
)

func TestPhoenixLimiter(t *testing.T) {
	limiter := NewEnhancedPhoenixLimiter(PhoenixLimiterConfig{
		Enable:            true,
		PermitsPerSecond:  2,
		BlackListCount:    1,
		BlacklistDuration: 30 * time.Second,
		RecordDuration:    30 * time.Second,
	})
	defer limiter.Close()

	// 测试正常请求
	res := limiter.Check("127.0.0.1")
	if !res.Allowed {
		t.Errorf("Expected allowed, got %v", res)
	}

	// 测试限流
	res = limiter.Check("127.0.0.1")
	if !res.Allowed {
		t.Errorf("Expected allowed, got %v", res)
	}

	// 第三次请求应被限流
	res = limiter.Check("127.0.0.1")
	if res.Allowed {
		t.Error("Expected to be limited")
	}

	// 测试黑名单
	res = limiter.Check("127.0.0.1")
	if res.Reason != "黑名单拦截" {
		t.Errorf("Expected blacklist, got %v", res.Reason)
	}

	// 测试黑名单移除
	limiter.RemoveFromBlacklist("127.0.0.1")
	res = limiter.Check("127.0.0.1")
	if !res.Allowed {
		t.Error("Expected allowed after removal")
	}
}

func TestStats(t *testing.T) {
	limiter := NewEnhancedPhoenixLimiter(PhoenixLimiterConfig{
		Enable:            true,
		PermitsPerSecond:  2,
		BlackListCount:    1,
		BlacklistDuration: 30 * time.Second,
		RecordDuration:    30 * time.Second,
	})
	defer limiter.Close()

	// 发送一些请求
	limiter.Check("127.0.0.1")
	limiter.Check("127.0.0.1")
	limiter.Check("127.0.0.1") // 被限流

	stats := limiter.GetStats()
	if stats.TotalRequests != 3 {
		t.Errorf("Expected 3 requests, got %d", stats.TotalRequests)
	}
	if stats.RejectedRequests != 1 {
		t.Errorf("Expected 1 rejected, got %d", stats.RejectedRequests)
	}
}
